﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GMS.MainClasses;
using GMS.ServiceFunctions.FunctionForControls;
using GMS.ServiceFunctions.Data;

namespace GMS.MenuContent
{
    public partial class MenuContent : ChildForms
    {
        FunctionForTreeView FFTV = new FunctionForTreeView();
        BindingSource bsMenu = new BindingSource();
        TreeNode SelectedNode = new TreeNode();
        ReturnData rd = new ReturnData();
        
        public MenuContent()
        {
            InitializeComponent();

            ConnectionString = "server=pavel;uid=pavel;pwd=123456;database=GMSDatabase";

            StoredProcedures = new String[2];

            StoredProcedures[0] = "[SelectMenuContent]";
            StoredProcedures[1] = "[MakeRootNode]";

        }

        private void MenuContent_Load(object sender, EventArgs e)
        {

        }

        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            TreeNode NewNode;

            if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));

                TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);
                NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

                if (DestinationNode.Level > NewNode.Level || DestinationNode == NewNode)
                {
                    MessageBox.Show("Недопустимая попытка перенести элемент!!!");
                }
                else
                {
                    DestinationNode.Nodes.Add((TreeNode)NewNode.Clone());

                    bsMenu.Filter = "[IdItem] = "+ NewNode.Tag;
                    Int32 i;
                    try
                    {
                        i = Convert.ToInt32(((DataRowView)bsMenu.List[0])["IdForm"].ToString());
                    }
                    catch
                    {
                        i = 3;
                    }
                    

                    MRF.ExecuteSqlCommand(StoredProcedures[1] + " " + NewNode.Tag + ","+i+"," + DestinationNode.Tag, ConnectionString);
                    DestinationNode.Expand();
                    //Remove Original Node
                    NewNode.Remove();
                }
            }
        }

        private void MakeRootToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode TN = treeView1.SelectedNode;
            if (MessageBox.Show("При перенесении эдемента в корень принадлежащая элементу форма будет удалена. \n\r \n\r  Продолжать?", "Предупреждение", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                try
                {
                    
                    treeView1.Nodes.Add((TreeNode)TN.Clone());
                    MRF.ExecuteSqlCommand(StoredProcedures[1]+" "+TN.Tag+", null, null", ConnectionString);
                    TN.Remove();
                    RefreshTreeView();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString(),"Ошибка!!!",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
        }

        private void RegisterMenuItem_Click(object sender, EventArgs e)
        {
            AddEditMenuItem AEMI = new AddEditMenuItem(AddEditMenuItem.EditMode.Добавление);
            AEMI.ConnectionString = ConnectionString;
            Int32 SN;
            try
            {
                SN = (Int32)treeView1.SelectedNode.Tag;
            }
            catch
            {
                SN = 0;
            }
            AEMI.IdMenu = SN;
            AEMI.MdiParent = MRF;
            AEMI.Show();
        }

        private void DeleteMenu_Click(object sender, EventArgs e)
        {
            AddEditMenuItem AEMI = new AddEditMenuItem(AddEditMenuItem.EditMode.Удаление);
            AEMI.ConnectionString = ConnectionString;
            if (treeView1.SelectedNode.Nodes.Count != 0)
            {
                MessageBox.Show("Удаление невозможно, присутствуют дочерние элементы!!!", "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            AEMI.IdMenu = Convert.ToInt32(treeView1.SelectedNode.Tag);
            AEMI.MdiParent = MRF;
            AEMI.Show();
        }

        private void RenameMenu_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null)
            {
                MessageBox.Show("Выберите позицию меню для редактирования.", "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            AddEditMenuItem AEMI = new AddEditMenuItem(AddEditMenuItem.EditMode.Редактирование);
            AEMI.ConnectionString = ConnectionString;
            AEMI.IdMenu = Convert.ToInt32(treeView1.SelectedNode.Tag);
            AEMI.MdiParent = MRF;
            AEMI.Show();
        }
        private void RefreshTreeView()
        {
            //bsMenu.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[0]);//rd.ReturnDataSetDB(ConnectionString, StoredProcedures[0]);
            bsMenu.DataSource = rd.ReturnDataSetDB(ConnectionString, StoredProcedures[0]);

            bsMenu.DataMember = "table";
            FFTV.FillTreeView(treeView1, bsMenu, "IdItem", "IdParentItem", "CaptionItem");
            SelectedNode.Expand();
        }

        private void MenuContent_Activated(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            AboutMenu AM = new AboutMenu();
            AM.Show();
        }

    }
}
